package org.zhuxian.cn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhuxian.cn.entity.Inlay;
import org.zhuxian.cn.mapper.InlayMapper;
import org.zhuxian.cn.service.InlayService;
import org.zhuxian.cn.utils.RedisUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class InlayServiceImpl implements InlayService {
    @Autowired
    private InlayMapper inlayMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void addInlay(Inlay inlay) {
        try {
            int result = inlayMapper.insert(inlay);
            if (result > 0) {
                log.info("添加灌注符成功，ID: {}", inlay.getId());
            } else {
                log.error("添加灌注符失败，ID: {}", inlay.getId());
            }
        } catch (Exception e) {
            log.error("添加灌注符时出现异常", e);
        }
    }

    @Override
    public void modifyInlay(Inlay inlay) {
        try {
            int result = inlayMapper.updateById(inlay);
            if (result > 0) {
                log.info("修改灌注符成功，ID: {}", inlay.getId());
            } else {
                log.error("修改灌注符失败，ID: {}", inlay.getId());
            }
        } catch (Exception e) {
            log.error("修改灌注符时出现异常", e);
        }
    }

    @Override
    public void deleteInlay(int id) {
        try {
            int result = inlayMapper.deleteById(id);
            if (result > 0) {
                log.info("删除灌注符成功，ID: {}", id);
            } else {
                log.error("删除灌注符失败，ID: {}", id);
            }
        } catch (Exception e) {
            log.error("删除灌注符时出现异常", e);
        }
    }

    @Override
    public Inlay getInlayById(int id) {
        Inlay inlay = redisUtils.get("inlay:" + id, Inlay.class);
        if (inlay == null) {
            inlay = inlayMapper.selectById(id);
            redisUtils.set("inlay:" + id, inlay);
        }
        return inlay;
    }

    @Override
    public List<Inlay> getAllInlay() {
        List<Inlay> inlays = redisUtils.get("inlay:all", List.class);
        if (inlays == null || inlays.isEmpty()) {
            inlays = inlayMapper.selectList(null);
            redisUtils.setEx("inlay:all", inlays, 3, TimeUnit.MINUTES);
        }
        return inlays;
    }

    @Override
    public List<Inlay> getInlayBySlot(String slot) {
        try {
            QueryWrapper<Inlay> wrapper = new QueryWrapper<>();
            wrapper.eq("slot", slot);
            return inlayMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("根据部位查询灌注符时出现异常", e);
            return null;
        }
    }
}